#!/bin/bash

# -e (-o errexit): exit immediately on error
# -u (-o nounset): treat unset variables as erros
# -o pipefail: propagate intermediate errors in pipelines
set -euo pipefail

CONFIG_HOME="${HOME}/.config/forem"
VAULT_PASSWORD_FILE="${CONFIG_HOME}/selfhost_ansible_vault_password"
INVENTORY_FILE=inventory/forem/setup.yml

main() {
  print_step "Verifying that pip is available"
  pip=$(command -v pip3 || echo -n "")
  if [ -z "$pip" ]; then
    print_error "Cannot find pip, aborting."
    exit 1
  fi

  print_step "Installing Python dependencies"
  pip3 install -r requirements.txt

  print_step "Generating Ansible Vault secret"
  if [ -f "$VAULT_PASSWORD_FILE" ]; then
    print_info "Password file already exists, skipping this step."
  else
    mkdir -p $CONFIG_HOME
    pwgen -1 24|tee $VAULT_PASSWORD_FILE
  fi

  print_step "Copying example inventory"
  if [ -f "$INVENTORY_FILE" ]; then
    print_info "Inventory file already exists, skipping this step."
  else
    cp -v inventory/example/setup.yml $INVENTORY_FILE
  fi

  print_step "Generating Vault secrets"
  echo -n $(pwgen -1 128) | ansible_vault_encrypt vault_secret_key_base
  echo -n $(xxd -g 2 -l 64 -p /dev/urandom | tr -d '\n') | ansible_vault_encrypt vault_imgproxy_key
  echo -n $(xxd -g 2 -l 64 -p /dev/urandom | tr -d '\n') | ansible_vault_encrypt vault_imgproxy_salt
  echo -n $(pwgen -1 128) | ansible_vault_encrypt vault_forem_postgres_password
  print_info "Use these secrets to replace the placeholders in ${INVENTORY_FILE}"
}

ansible_vault_encrypt() {
  ansible-vault encrypt_string --stdin-name $1
}

### OUTPUT HELPERS
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NO_COLOR='\033[0m'

color_print() {
  local color=$1
  shift
  # Only write colorized output when STDOUT is a terminal
  if [ -t 1 ]; then
    printf "\n${color}$*${NO_COLOR}\n"
  else
    printf "\n$*\n"
  fi
}

print_step() {
  color_print $GREEN $@
}

print_info() {
  color_print $YELLOW $@
}

print_error() {
  color_print $RED $@ 1>&2 # erros go to STDERR
}
### END OUTPUT HELPERS

main $@
